package cn.itcast.nems.config.mybatisplus;

import cn.itcast.nems.common.account.AccountHolder;
import cn.itcast.nems.common.tenant.TenantInfoHolder;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * author: yong.li
 * create: 2023-08-17 14:06:19
 **/
@Component
public class EMSv2MetaObjectHandler implements MetaObjectHandler {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void insertFill(MetaObject metaObject) {
        logger.info("start insert fill ....");
        this.strictInsertFill(metaObject, "createdDatetime", LocalDateTime::now, LocalDateTime.class);
        TenantInfoHolder.getTenantInfo().ifPresent(tenantInfo -> this.strictInsertFill(metaObject, "subtenantId", tenantInfo::subtenantId, Integer.class));
        AccountHolder.getAccount().ifPresent(accountId -> this.strictInsertFill(metaObject, "createdBy", () -> accountId, String.class));
        this.strictInsertFill(metaObject, "deletedFlag", () -> false, Boolean.class);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        logger.info("start update fill ....");
        this.strictUpdateFill(metaObject, "modifiedDatetime", LocalDateTime::now, LocalDateTime.class);
        AccountHolder.getAccount().ifPresent(accountId -> this.strictUpdateFill(metaObject, "modifiedBy", () -> accountId, String.class));
    }
}
